<template>

    <el-form :model="receiverInfo"
    ref="receiverInfoForm"
    label-width="150px">

    <el-form-item v-if="isCustomerListLoaded && customerAddrList.length > 0" label="客户地址" style="width: 100%">
      <el-select v-model="selectedaddressId" placeholder="请选择客户地址" @change="handleAddrChange" style="width: 18%">
        <el-option
            v-for="addr in this.customerAddrList"
            :key="addr.addressId"
            :label="`${addr.consignee}-${addr.phone}-${addr.country}-${addr.state}-${addr.city}-${addr.district}`"
            :value="addr.addressId"
        ></el-option>
      </el-select>

      <el-button style="margin-left: 30px" type="primary"  @click="addCustomerAddr">新增地址</el-button>

      <el-button style="margin-left: 30px"   @click="handledeleteAddr">删除地址</el-button>

    </el-form-item>

    <el-form-item label="收货人姓名：">
        <el-input v-model="receiverInfo.consignee"placeholder="请输入收货人姓名" style="width: 200px"></el-input>
    </el-form-item>
    <el-form-item label="手机号码：">
        <el-input v-model="receiverInfo.phone" style="width: 200px"placeholder="请输入手机号码">
        </el-input>
    </el-form-item>
    <el-form-item label="邮政编码：">
        <el-input v-model="receiverInfo.zipcode" style="width: 200px"placeholder="请输入邮政编码">
        </el-input>
    </el-form-item>
    <el-form-item label="所在区域："placeholder="请选择所在区域">
        <el-cascader
                v-model="selectedOptions"
                :options="options"
                @change="handleChange"
                clearable
                style="width: 300px;"
        ></el-cascader>
    </el-form-item>
    <el-form-item label="详细地址：">
        <el-input v-model="receiverInfo.streetAddress" type="textarea" rows="3"placeholder="请输入详细地址">
        </el-input>
    </el-form-item>

    </el-form>

    <div style="text-align: center ; margin-top: 20px" >
        <el-button size="medium" @click="handlePrev">上一步，修改基本信息</el-button>
        <el-button type="primary" size="medium" @click="handleNext">下一步，填写商品列表</el-button>
    </div>


  <el-dialog title="新增地址信息"
             v-model="addrDialogVisible"
             width="40%">
    <el-form :model="form"
             ref="receiverInfoForm"
             label-width="150px">

      <el-form-item label="收货人姓名：">
        <el-input v-model="form.consignee"placeholder="请输入收货人姓名" style="width: 200px"></el-input>
      </el-form-item>
      <el-form-item label="手机号码：">
        <el-input v-model="form.phone" style="width: 200px"placeholder="请输入手机号码">
        </el-input>
      </el-form-item>
      <el-form-item label="邮政编码：">
        <el-input v-model="form.zipcode" style="width: 200px"placeholder="请输入邮政编码">
        </el-input>
      </el-form-item>
      <el-form-item label="所在区域："placeholder="请选择所在区域">
        <el-cascader
            v-model="addOptions"
            :options="options"
            @change="handleChange"
            clearable
            style="width: 300px;"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="详细地址：">
        <el-input v-model="form.streetAddress" type="textarea" rows="3"placeholder="请输入详细地址">
        </el-input>
      </el-form-item>
    </el-form>
      <span slot="footer" class="dialog-footer" style="margin-left: 37%">
        <el-button @click="addrDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handlAddInfo">确 定</el-button>
      </span>
  </el-dialog>


  <el-dialog title="删除地址信息"
             v-model="deleteDialogVisible"
             width="60%">
    <div class="table-layout">
      <el-table :data="deleteaddrList" border>
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="consignee" label="收货人" width="100"></el-table-column>
        <el-table-column prop="phone" label="联系电话" width="180"></el-table-column>
        <el-table-column prop="zipcode" label="邮政编码" width="110"></el-table-column>
        <el-table-column label="地址" width="330">
          <template  #default="scope">
            {{ scope.row.state + ' - ' + scope.row.city + ' - ' + scope.row.district }}
          </template>
        </el-table-column>
        <el-table-column prop="streetAddress" label="详细地址" width="200"></el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="120">
          <template #default="scope">
            <el-button link type="primary" icon="Delete" @click="deleteAddr(scope.row)"
                       v-hasPermi="['system:order:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getDeleteAddrList"
          style="width: 80px; height: 50px;"
      />



      <span slot="footer" class="dialog-footer" style="margin-left: 45% ; margin-top: 20px">
                 <el-button @click="deleteDialogVisible = false">取 消</el-button>
                 <el-button type="primary" @click="handleAddMerList">确 定</el-button>
             </span>


    </div>

  </el-dialog>

</template>

<script>

    import * as areaData from 'element-china-area-data';
    import {getCustomer,listAddr,addAddr,delAddr,delCustomerAddr} from "@/api/system/addr.js";

    export default {
        name: "ReceiverInfo",

      props:{
        customerId:{
          type:Number,
          default:null
        }
      },


        data(){
            return{
              queryParams: {
                pageNum: 1,
                pageSize: 10,
                customerId:null
              },
              total: null,
              form:{},
              addrDialogVisible:false,
              deleteDialogVisible:false,
              receiverInfo: {
                addressId: null,
                city: null,
                consignee: null,
                country: '中国',
                createBy: null,
                createTime: null,
                customerId: null,
                district: null,
                isPickup: 0,
                phone: null,
                remark: null,
                state: null,
                streetAddress: null,
                updateBy: null,
                updateTime: null,
                zipcode: null
              },
                selectedOptions:{},
                addOptions:{},
                options:areaData.regionData,
                customerAddrList:{},
                deleteaddrList:{},
                selectedaddressId:{},
                isCustomerListLoaded: false


            }
        },
      watch: {
        customerId: {
          handler(newVal, oldVal) {
            console.log('customerId changed from', oldVal, 'to', newVal);
            if (newVal !== null && newVal !== undefined) {
              this.$nextTick(() => {
                this.selectedaddressId = null;
                this.getCustomerList();
                this.queryParams.customerId = newVal
                this.getDeleteAddrList()
              });
            }
          },
          immediate: true
        },
        receiverInfo: {
          handler(newValue) {
            this.$emit('input', newValue);
          },
          deep: true
        }
      },

      mounted() {

      },

      methods:{

        deleteAddr(row){

          const customerAddr = {
            customerId: this.customerId,
            addressId: row.addressId
          }

          this.$confirm('确定删除该地址吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            delCustomerAddr(customerAddr).then(response => {
              this.$message.success("删除地址成功");
              this.deleteDialogVisible = false
              this.getDeleteAddrList()
              this.getCustomerList()
            })
          }).catch(() => {

          })


        },

        handlAddInfo(){
          const processData = {
            customerId : this.customerId,
            consignee: this.form.consignee,
            country: "中国",
            phone: this.form.phone,
            state: this.codeToText(this.addOptions[0]),
            city: this.codeToText(this.addOptions[1]),
            district: this.codeToText(this.addOptions[2]),
            streetAddress: this.form.streetAddress,
            zipcode: this.form.zipcode,
          };

          this.$confirm('确定新增该地址吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            addAddr(processData).then(response => {
              this.$message.success("新增地址成功");
              this.getDeleteAddrList()
              this.addrDialogVisible =false
              this.getCustomerList()
            });
          })



        },

        handledeleteAddr(){
          this.deleteDialogVisible = true;
        },

        addCustomerAddr(){

          this.addrDialogVisible = true;

        },



        handleAddrChange(){

          this.customerAddrList.forEach(item =>{
            if(item.addressId === this.selectedaddressId){
              this.receiverInfo = {
                addressId: item.addressId,
                consignee : item.consignee,
                phone : item.phone,
                zipcode : item.zipcode,
                streetAddress:item.streetAddress
              }

              this.selectedOptions = this.namesToCodes([item.state,item.city,item.district])

            }
          })

        },

        async getCustomerList() {
          try {
            const response = await getCustomer(this.customerId);
            this.customerAddrList = response.data || []; // 确保 customerlist 是一个数组
            console.log('customerlist fetched:', this.customerAddrList);
            this.$nextTick(() => {
              this.isCustomerListLoaded = true;
              console.log('isCustomerListLoaded set to true');
            });
          } catch (error) {
            console.error('Error fetching customer list:', error);
          }
        },


        getDeleteAddrList(){
          listAddr(this.queryParams).then(response => {
            this.total = response.total;
            this.deleteaddrList = response.rows;
          })
        },

          handleChange(){

            console.log(this.selectedOptions);
            this.codeToText(this.selectedOptions[0]);
            this.codeToText(this.selectedOptions[1]);
            this.codeToText(this.selectedOptions[2]);
          },

          codeToText(code) {
            const find = (data, code) => {
              for (let key in data) {
                if (data[key].value === code) {
                  return data[key].label;
                }
                if (data[key].children) {
                  const result = find(data[key].children, code);
                  if (result) return result;
                }
              }
              return null;
            };

            return find(areaData.regionData, code);
          },

        namesToCodes(names) {
          let codes = [];
          let currentData = areaData.regionData;
          names.forEach(name => {
            let found = false;
            for (let key in currentData) {
              if (currentData[key].label === name) {
                codes.push(currentData[key].value);
                if (currentData[key].children) {
                  currentData = currentData[key].children;
                  found = true;
                  break;
                } else {
                  found = true;
                  break;
                }
              }
            }
            if (!found) {
              console.warn(`Could not find the area with name: ${name}`);
              return [];
            }
          });
          return codes;
        },

            handlePrev() {
                this.$emit('prevStep')
            },
            handleNext(){
                this.$emit('nextStep')
            },

          getselectedOptions(){
            return this.selectedOptions;
          }

        }
    }
</script>

<style scoped>

</style>